﻿using System;
using System.Collections.Generic;
using System.Data;

namespace YJKDataBase
{
	public class SqliteSubjectTable : ISubjectTable
	{
		public SqliteSubjectTable(SqliteDatabase db)
		{
			this.mDatabase = db;
		}

		public DbSubject this[Guid id]
		{
			get
			{
				DataTable dataTable = this.mDatabase.ExecQuery(string.Format("select [SubjectName],[Version] from [SubjectTable] where [GUID]='{0}'", id.ToString()));
				if (dataTable != null)
				{
					DbSubject dbSubject = new DbSubject(dataTable.Rows[0][0].ToString().Trim(), id);
					dbSubject.Version = dataTable.Rows[0][1].ToString();
					dbSubject.SetDatabase(this.mDatabase);
					return dbSubject;
				}
				return null;
			}
		}

		public List<DbSubject> AllSubject()
		{
			List<DbSubject> list = new List<DbSubject>();
			DataTable dataTable = this.mDatabase.ExecQuery(string.Format("select [Name],[Version],[GUID] from [SubjectTable]", Array.Empty<object>()));
			if (dataTable != null)
			{
				for (int i = 0; i < dataTable.Rows.Count; i++)
				{
					DbSubject dbSubject = new DbSubject(dataTable.Rows[i][0].ToString().Trim(), new Guid(dataTable.Rows[i][2].ToString()));
					dbSubject.Version = dataTable.Rows[i][1].ToString();
					dbSubject.SetDatabase(this.mDatabase);
					list.Add(dbSubject);
				}
			}
			return list;
		}

		public string GetVersion()
		{
			string result = "";
			string sqlStr = string.Format("select Version from SubjectTable", Array.Empty<object>());
			DataTable dataTable = this.mDatabase.ExecQuery(sqlStr);
			if (dataTable != null && dataTable.Rows.Count > 0)
			{
				result = dataTable.Rows[0]["Version"].ToString();
			}
			return result;
		}

		public void SetVersion(string ver)
		{
			string sqlStr = string.Format("UPDATE SubjectTable SET Version = '{0}'", ver);
			this.mDatabase.ExecQuery(sqlStr);
		}

		private SqliteDatabase mDatabase;
	}
}
